package com.czmh.etc.onlinepubsys.utils.wj;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.czmh.etc.onlinepubsys.constants.ue.BusinessType;
import com.czmh.etc.onlinepubsys.enums.ue.ApiCodeEnum;
import com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult;
import com.czmh.etc.onlinepubsys.response.ue.ApiResponse;
import com.czmh.etc.onlinepubsys.utils.RedisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.czmh.etc.common.core.utils.MSignUtils;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.entity.StringEntity;

@Component
@Slf4j
public class WjHttpUtil {

    public static String url;
    public static String appId;
    public static String appsecurity;


    @Value("${wangji.testurl}")
    private String url0;
    @Value("${wangji.appId}")
    private String appId0;
    @Value("${wangji.appsecurity}")
    private String appsecurity0;

    @Autowired
    private RedisUtil redisUtil;

    @PostConstruct
    public void init() {
        url = url0;
        appId = appId0;
        appsecurity = appsecurity0;
    }

    public static ApiResponse get(String baseURL, String jsonData) {
        ApiResponse result = null;
        String uri = url + baseURL;
        //1.请求体
        ObjectMapper mapper = new ObjectMapper();
        try {
            HashMap<String, String> body = mapper.readValue(jsonData, HashMap.class);
            body.put("appId", appId);
            body.put("signType", "MD5");
            body.put("timestamp", String.valueOf(System.currentTimeMillis()));//每个时间戳有效时间是100min
            //2.计算密钥
            String sign = MSignUtils.buildSign(body, appsecurity);

            body.put("sign", sign);
            StringBuilder queryString = new StringBuilder();
            for (HashMap.Entry<String, String> entry : body.entrySet()) {
                queryString.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            queryString.deleteCharAt(queryString.length() - 1); // 删除最后的"&"

            // 构建完整的URL
            String fullURL = uri + "?" + queryString.toString();

            // 创建HttpClient实例
            HttpClient httpClient = HttpClients.createDefault();

            // 创建HttpGet实例
            HttpGet httpGet = new HttpGet(fullURL);

            // 执行GET请求
            HttpResponse response = httpClient.execute(httpGet);

            // 获取响应内容
            String resultData = EntityUtils.toString(response.getEntity(), "UTF-8");

            // 返回响应内容
            System.out.println(resultData);

            result = JSON.parseObject(resultData, ApiResponse.class);
            result.setRspData(resultData);
            return result;
        } catch (
                SocketTimeoutException exception) {
            log.error("万集请求超时", exception);
            ApiResponse r = new ApiResponse();
            r.setCode(ApiCodeEnum.SOCKET_TIME_OUT.getCode());
            r.setMsg(ApiCodeEnum.SOCKET_TIME_OUT.getMessage());
            return r;
        } catch (
                SocketException exception) {
            log.error("万集连接失败", exception);
            ApiResponse r = new ApiResponse();
            r.setCode(ApiCodeEnum.CONNECTION_REST.getCode());
            r.setMsg(ApiCodeEnum.CONNECTION_REST.getMessage());
            return r;
        } catch (Exception e) {
            log.error("万集请求失败", e);
            throw new RuntimeException(e);
        }
    }


    public static ApiResponse post(String baseURL, String jsonData) {
        ApiResponse result = null;
        String uri = url + baseURL;
        //1.请求体
        ObjectMapper mapper = new ObjectMapper();
        try {
            HashMap<String, String> body = mapper.readValue(jsonData, HashMap.class);
            body.put("appId", appId);
            body.put("signType", "MD5");
            body.put("timestamp", String.valueOf(System.currentTimeMillis()));//每个时间戳有效时间是100min
            //2.计算密钥
            String sign = MSignUtils.buildSign(body, appsecurity);
            body.put("sign", sign);
            StringBuilder queryString = new StringBuilder();
            for (HashMap.Entry<String, String> entry : body.entrySet()) {
                if (entry.getKey() != "file") {
                    queryString.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
            }
            queryString.deleteCharAt(queryString.length() - 1); // 删除最后的"&"

            // 构建完整的URL
            String fullURL = uri + "?" + queryString.toString();

            // 创建HttpClient实例
            CloseableHttpClient httpClient = HttpClients.createDefault();

            // 创建HTTP POST请求
            HttpPost httpPost = new HttpPost("http://example.com/api/endpoint");

            // 设置请求的JSON内容
            JSONObject jsonObject = JSON.parseObject(jsonData);
            JSONObject newJson = new JSONObject();
            newJson.put("file", jsonObject.getString("file"));
            String JsonData = JSONObject.toJSONString(newJson);
            StringEntity entity = new StringEntity(JsonData);
            entity.setContentType("application/json");
            httpPost.setEntity(entity);

            try {
                // 执行请求并获得响应
                CloseableHttpResponse response = httpClient.execute(httpPost);

                // 从响应中提取JSON字符串
                String jsonResponse = EntityUtils.toString(response.getEntity());

                // 关闭响应
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            log.error("万集请求失败", e);
            throw new RuntimeException(e);
        }

        return result;
    }

    /**
     * //TODO 转换header
     *
     * @param headers
     * @return
     */
    private static Header[] parseHeader(Map<String, String> headers) {
        if (null == headers || headers.isEmpty()) {
            return getDefaultHeaders();
        }
        Header[] allHeader = new BasicHeader[headers.size()];
        int i = 0;
        for (String str : headers.keySet()) {
            allHeader[i] = new BasicHeader(str, headers.get(str));
            i++;
        }
        return allHeader;
    }

    /**
     * //TODO 默认header
     *
     * @return
     */
    private static Header[] getDefaultHeaders() {
        Header[] allHeader = new BasicHeader[2];
        allHeader[0] = new BasicHeader("Content-Type", "application/x-www-form-urlencoded");
        allHeader[1] = new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
        return allHeader;
    }
}
